import React from 'react';
import { LogoutOutlined, SettingOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import { Avatar, Menu, Spin, Modal, Form, Input, Typography } from 'antd';
import { history, connect } from 'umi';
import { getPageQuery, clearLocalStorage } from '@/utils';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import perLogo from '@/assets/images/login.png';
const { confirm } = Modal;
class AvatarDropdown extends React.Component {
  state = {
    modalVisible: false,
  };
  onMenuClick = (event) => {
    const { key } = event;
    if (key === 'logout') {
      confirm({
        title: '您确定要退出登录吗？',
        icon: <ExclamationCircleFilled />,
        cancelText: '取消',
        okText: '确定',
        onOk() {
          const { redirect } = getPageQuery();
          if (window.location.pathname !== '/user/login' && !redirect) {
            clearLocalStorage();
            history.push('/user/login');
          }
        },
        onCancel() {},
      });
      return;
    }
    if (key === 'password') {
      this.setState({
        modalVisible: true,
      });
      return;
    }
  };
  handlePasswordCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };
  render() {
    const currentUser = JSON.parse(localStorage.getItem('userInfo'));
    const { modalVisible } = this.state;
    const layout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 16,
      },
    };
    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        <Menu.Item key="password">
          <SettingOutlined />
          修改密码
        </Menu.Item>
        <Menu.Item key="logout">
          <LogoutOutlined />
          退出登录
        </Menu.Item>
      </Menu>
    );
    return (
      <>
        {currentUser && currentUser.user.personal.lastName ? (
          <HeaderDropdown overlay={menuHeaderDropdown}>
            <span className={`${styles.action} ${styles.account}`}>
              <Avatar size="small" className={styles.avatar} src={perLogo} alt="avatar" />
              <span className={`${styles.name} anticon`}>{currentUser.user.personal.lastName}</span>
            </span>
          </HeaderDropdown>
        ) : (
          <span className={`${styles.action} ${styles.account}`}>
            <Spin
              size="small"
              style={{
                marginLeft: 8,
                marginRight: 8,
              }}
            />
          </span>
        )}
        {modalVisible && (
          <Modal
            title="修改密码"
            visible={this.state.modalVisible}
            // onOk={this.handlePasswordOk}
            onCancel={this.handlePasswordCancel}
            confirmLoading={this.props.loading}
          >
            <Form
              {...layout}
              name="basic"
              initialValues={{
                remember: true,
              }}
              onValuesChange={(value) => {
                const keys = Object.keys(value);
                if (keys.indexOf('password') !== -1) {
                  this.setState({
                    password: {
                      validateStatus: 'success',
                      msg: null,
                    },
                  });
                }
              }}
            >
              <Form.Item label="用户名" name="barcode">
                {currentUser?.user.personal.lastName}
              </Form.Item>
              <Form.Item label="原密码" name="password" required>
                <Input.Password visibilityToggle />
              </Form.Item>
              <Form.Item
                label="新密码"
                name="newPassword"
                dependencies={['password']}
                rules={[
                  {
                    required: true,
                    message: '请输入新密码',
                  },
                ]}
              >
                <Input.Password visibilityToggle />
              </Form.Item>
              <Form.Item
                label="新密码确认"
                required
                name="confirmPassword"
                dependencies={['password']}
                rules={[
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (getFieldValue('password') === value) {
                        return Promise.reject(new Error('新密码不能和旧密码一样，请重新输入'));
                      }
                      if (getFieldValue('newPassword') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次密码输入不一致，请重新输入'));
                    },
                  }),
                ]}
              >
                <Input.Password visibilityToggle />
              </Form.Item>
              <div
                style={{
                  textAlign: 'center',
                }}
              >
                <Typography.Text type="warning">
                  密码为8到16位,必须包含数字、字母、特殊字符
                </Typography.Text>
              </div>
              <div
                style={{
                  textAlign: 'center',
                }}
              >
                <Typography.Text type="warning">
                  特殊字符: {`~!@#$%^&*()\-_+={}:;'",.?<>\\/\[\]|\``}
                </Typography.Text>
              </div>
            </Form>
          </Modal>
        )}
      </>
    );
  }
}
export default connect(({}) => ({}))(AvatarDropdown);
